import json
from pprint import pprint
from random import randint

from django.test import TestCase, Client

from jqgame.basegame import GameType
from jqpackage.models import UserPackageGoods
from juqiadmin.models import get_wxuser_finance, get_game_finance, update_finnce_profit
from juqiadmin.serializers import UserPackageDetailedSerializer
from juqiadmin.tests import admin_login
from quanjushang.models import QuanjushangGame, QuanjushangSonGame
from quanjushang.ser import JuqigoodSer
from warehouse.models import JuqiGood
from warehouse.serializers import JuqiGoodSerializer
from wxcloudrun.views import order_uuid
from wxuser.models import Users, UserOrder, UserRefinedOrder


def gen_user():
    for i in range(10):
        Users.objects.create(
            openid="12121212121212121211212" + str(i),
            nickname="admin_" + str(i),
            realname="cc" + str(i),
            telephone="11111111111" + str(i),
            need_help=True,
            stored_money=randint(1000, 10000),
            score=randint(1000, 10000),
            hunjing=randint(10000, 1000000000),
        )

    return Users.objects.create(
        openid="12121212121212121211212",
        nickname="admin_a",
        realname="cc",
        telephone="11111111111",
        need_help=True,
        is_real=True,
        stored_money=int(1e8),
        score=int(1e8),
        hunjing=int(1e8),
    )


def create_goods():
    for i in range(5):
        JuqiGood(
            name="小汽车" + str(randint(100, 10000)),
            display_url="123" + str(randint(100, 10000)),
            price=500 + randint(1000, 10000),
            recovery_price=100 + randint(0, 1000),
            game_type="全局赏",
            ip_family="123" + str(randint(100, 10000)),
            # 商品详细介绍
            detail="123" + str(randint(100, 10000)),
        ).save()


def create_orders():
    create_goods()
    users = Users.objects.filter(deleted=False).all()
    goods = JuqiGood.objects.filter(deleted=False).all()

    game = QuanjushangGame.objects.create(
        name="test池子", cover_url="123", user_limit=1, price=10, game_num=50
    )
    son_game_ = []
    for v in range(1, 5 + 1):
        i = {"game_uuid": game.uuid, "user_limit": 1, "price": 1000, "box_num": v}
        son_game_.append(QuanjushangSonGame(**i))
    son_games = QuanjushangSonGame.objects.bulk_create(son_game_)

    for user in users:
        for son_game in son_games:
            user_order = UserOrder.objects.create(
                user_uuid=user.uuid,
                game_type=GameType.quanjushang.value,
                game_uuid=game.uuid,
                game_name=game.name,
                son_uuid=son_game.uuid,
                box_num=son_game.box_num,
                num=game.game_num,
                money=game.price,
                price=game.price,
                hunjing=0,
                score=0,
                weixin=0,
                orderid=order_uuid("CS_"),
            )
            for good in goods:
                for i in range(randint(1, 5)):
                    UserPackageGoods(
                        order_uuid=user_order.uuid,
                        good_uuid=good.uuid,
                        user_uuid=user.uuid,
                        good_level_title="A赏品",
                        game_type=GameType.quanjushang.value,
                        game_uuid=game.uuid,
                        game_son_uuid=son_game.uuid,
                        game_box_num=son_game.box_num,
                        order_num=i,
                    ).save()
                    finance = get_wxuser_finance(
                        GameType.quanjushang, user.uuid, game.uuid
                    )
                    finance_game = get_game_finance(gameType=GameType.quanjushang)
                    _all_raffle_income = randint(10000, 1000000)
                    _all_raffle_cost = randint(10, 10000)
                    finance.all_raffle_income += _all_raffle_income
                    finance.all_raffle_cost += _all_raffle_cost
                    finance_game.all_raffle_income += _all_raffle_income
                    finance_game.all_raffle_cost += _all_raffle_cost
                    update_finnce_profit(finance)
                    update_finnce_profit(finance_game)
                    finance.save()
                    finance_game.save()


class JqPackageTest(TestCase):
    def setUp(self):
        self.user = gen_user()
        self.wx_c = Client(HTTP_X_WX_OPENID=self.user.openid)
        self.admin_c = Client()

    def test_package_list(self):
        create_orders()
        # res = self.wx_c.get("/api/package/goods")
        # data = json.loads(res.content)
        # pprint(data)

        res = self.wx_c.get("/api/package/goods", {"display": 1})
        data = json.loads(res.content)
        pprint(data)

        # res = self.wx_c.get("/api/package/goods", {"query": "lock"})
        # data = json.loads(res.content)
        # pprint(data)
        #
        # res = self.wx_c.get("/api/package/goods", {"sort": "money_high"})
        # data = json.loads(res.content)
        # pprint(data)
        # res = self.wx_c.get("/api/package/goods", {"sort": "money_low"})
        # data = json.loads(res.content)
        # pprint(data)

    def test_correct(self):
        # admin_login(self.admin_c)  # 登录管理员
        create_orders()
        res = self.admin_c.put(
            "/api/admin/correct",
            content_type="application/json",
        )
        data = json.loads(res.content)
        pprint(data)

    def test_package_refined(self):
        admin_login(self.admin_c)  # 登录管理员
        create_orders()
        goods_list = UserPackageGoods.objects.filter(user_uuid=self.user.uuid)
        goods_uuid_list = []
        for goods in goods_list:
            goods_data = UserPackageDetailedSerializer(goods).data
            goods_uuid_list.append(goods_data["uuid"])
        pprint(goods_uuid_list)

        res = self.wx_c.post(
            "/api/delivery/express",
            {
                "express": {
                    "express_name": "蔡徐坤",
                    "express_phone": "13888888888",
                    "express_area": "北京市 北京市 朝阳区",
                    "express_address": "一个不存在的地方",
                },
                "default": True,
            },
            content_type="application/json",
        )
        data = json.loads(res.content)
        pprint(data)

        res = self.wx_c.put(
            "/api/package/apply/delivery",
            {"goods": goods_uuid_list[0:10]},
            content_type="application/json",
        )
        data = json.loads(res.content)
        pprint(data)
        express_info_uuid = data["data"]["user_express"]["uuid"]
        res = self.wx_c.put(
            "/api/package/delivery",
            {
                "express_info_uuid": express_info_uuid,
                "goods": goods_uuid_list,
                "pay_type": "stored_money",
                "remark": "我不要这个",
            },
            content_type="application/json",
        )
        data = json.loads(res.content)
        pprint(data)

        res = self.wx_c.get(
            "/api/delivery/list",
        )
        data = json.loads(res.content)
        pprint(data)
        order_uuid = data["data"]["list"][0]["uuid"]
        res = self.wx_c.get("/api/delivery/detailed", {"uuid": order_uuid})
        data = json.loads(res.content)
        pprint(data)

        res = self.wx_c.get("/api/delivery/list", {"state": "1"})
        data = json.loads(res.content)
        pprint(data)

        res = self.admin_c.get("/api/admin/delivery", {"state": "0"})

        data = json.loads(res.content)
        pprint(data)

        res = self.admin_c.get("/api/admin/delivery/detailed", {"uuid": order_uuid})
        data = json.loads(res.content)
        pprint(data)

        res = self.admin_c.put(
            "/api/admin/delivery/verify?uuid=" + order_uuid,
            {"delivery_name": "abc", "delivery_number": "12121212121212121"},
            content_type="application/json",
        )
        data = json.loads(res.content)
        pprint(data)
        res = self.wx_c.put(
            "/api/delivery/confirm",
            {"uuid": order_uuid},
            content_type="application/json",
        )
        data = json.loads(res.content)
        pprint(data)

        res = self.wx_c.get("/api/delivery/detailed", {"uuid": order_uuid})
        data = json.loads(res.content)
        pprint(data)
        res = self.wx_c.put(
            "/api/package/refined",
            {"goods": goods_uuid_list},
            content_type="application/json",
        )
        data = json.loads(res.content)
        pprint(data)
        # user_order_refined = UserRefinedOrder.objects.filter(deleted=False).first()
        # res = self.admin_c.get(
        #     "/api/admin/user/record/refined/goods",
        #     {"order_refined_uuid": user_order_refined.uuid},
        # )
        # data = json.loads(res.content)
        # pprint(data)

    def test_package_lock_and_unlock(self):
        create_orders()
        goods_list = UserPackageGoods.objects.filter(user_uuid=self.user.uuid)
        goods_uuid_list = []
        for goods in goods_list:
            goods_data = UserPackageDetailedSerializer(goods).data
            goods_uuid_list.append(goods_data["uuid"])
        good_list = JuqiGood.objects.filter(deleted=False)
        good_uuid_list = []

        for good in good_list:
            good_data = JuqiGoodSerializer(good).data
            good_uuid_list.append({"uuid": good_data["uuid"], "count": 100})
        pprint(good_uuid_list)

        res = self.wx_c.put(
            "/api/package/lock",
            {"goods": good_uuid_list, "display": 1},
            content_type="application/json",
        )
        data = json.loads(res.content)
        pprint(data)
        res = self.wx_c.put(
            "/api/package/lock",
            {"goods": good_uuid_list, "display": 1},
            content_type="application/json",
        )
        data = json.loads(res.content)
        pprint(data)

        res = self.wx_c.put(
            "/api/package/unlock",
            {"goods": good_uuid_list, "display": 1},
            content_type="application/json",
        )
        data = json.loads(res.content)
        pprint(data)

        res = self.wx_c.put(
            "/api/package/unlock",
            {"goods": good_uuid_list, "display": 1},
            content_type="application/json",
        )
        data = json.loads(res.content)
        pprint(data)
